//当前激活tab
var activeTab = "main";



//agentId，保留，当前未使用，默认为""
var agentId = "";
//userId
var userId = "";

//各功能聊天室对话框
var voipMsgWindow = null;

// 集成文档请参考 https://docs.starrtc.com/en/docs/web-7.html

var aecRequestBaseURL = "https://www.starrtc.com/aec";				//开启AEC后，才生效，从此url获取各种列表信息
// var privateURL = "demo.starrtc.com";								//后端服务地址，可为ip，也可为域名
// var webrtcIP = "123.103.93.74";										//后端服务地址，必须为ip（目前只有chrome72以上支持设置成域名），webrtc ip，用于设置webrtc udp ip，用于setSrcServerInfo，setVdnServerInfo，setVoipServerInfo接口，不设置时与后端服务地址privateURL一致
// var privateURL = "192.168.1.222";
// var webrtcIP = "192.168.1.222";
var privateURL = "110.249.213.119";
var webrtcIP = "110.249.213.119";
//设置日志等级，开启低等级日志会包含高等级日志，如开启DEBUG，则同时开启INFO、WARN、ERROR，默认为开启DEBUG
StarRtc.InitlogLevel(LOG_LEVEL.LOG_LEVEL_DEBUG);

//创建SDK对象
StarRtc.Instance = new StarRtc.StarSDK();

////////////////////////私有云改配置///////////////////////
///////////////////////以下privateURL需替换为私有部署IP////

//StarRtc.Instance.setConfigUseAEC(true);    							//是否开启AEC

StarRtc.Instance.setMsgServerInfo(privateURL, 19903) 					//ip, websocket port  //需要手动从浏览器输入 https://ip:29991 信任证书
StarRtc.Instance.setVoipServerInfo(privateURL, 10086, 10087, 10088, webrtcIP) 	//ip, voipServer port, websocket port, webrtc port, webrtc ip //需要手动从浏览器输入 https://ip:29992 信任证书


//点击返回触发的函数
var currFunc = {
    "exit": undefined
};


function showVoipTab() {
    activeTab = "voip";
    $(".tab").hide();
    $("#voipTab").slideDown(2000, enterVoipFunc);
}

function bindEvent() {
    $(".backButton").each(function (id, ele) {
        $(ele).bind("click", function () {
            showMainTab();
            if (currFunc.exit != undefined) {
                currFunc.exit();
            }
        });
    });

    $("#voipMessageButton").bind("click", function () {
        $("#voipVideoZone").css("width", "85%");
        $("#voipVideoZone").css("float", "left");
        $("#voipMessageButton").hide();
        voipMsgWindow.show();
    });

    $("#voipCalling").bind("click", openCallDlg);
    $("#videoClose").bind("click", hangupVOIP);
     $("#voipHangup1").bind("click", hangupVOIP);
      $("#voipHangup1").bind("click", hangupVOIP);

    $("#voipSmallVideo").bind("click", switchVoipVideo);
    $("#voipBigVideo").bind("click", switchVoipVideo);

}

//////////////////////////////////////////////star box end////////////////////////////////////////
//////////////////////////////////////////////voip////////////////////////////////////////////
var currRoom = null;
var voipResponseDlg;
var voipConnectDlg;
var voipCallDlg;
//voip 仅音频标志位
var voipAudio = false;

function enterVoipFunc() {
    currFunc.exit = exitVoipFunc;
}

//退出voip
function exitVoipFunc() {
    if (currRoom != null) {
        currRoom.leaveRoom();
        currRoom.sigDisconnect();
        currRoom = null;
    }
}

//打开voip呼叫页面
function openCallDlg() {
    // var isfinish = $("#isfinish").val();
    // if(isfinish==3){
    //     alert("此账号正在踏勘中");
    //     return;
    // }
    var makeTime = new Date(Date.parse($('#makeTime').val().trim()));
    var data = new Date(Date.parse(new Date()));

    // if (Date.parse($('#makeTime').val())>Date.parse($('#date').val())){
    //     alert("还没到踏勘时间")
    //     return;
    // }
    var targetUid = $('#username').val().trim();
    if (targetUid == null || targetUid == undefined || targetUid == "") {
        alert("对方ID不能为空");
        return;
    }
    $("#calleeId").html(targetUid);
    voipCallDlg.dialog("open");
}

//开始voip呼叫
function callingVOIP() {
    var targetUid = $('#targetUserId').val().trim();
    if (targetUid == null || targetUid == undefined || targetUid == "") {
        alert("对方ID不能为空");
        return;
    }
    voipCallDlg.dialog("close");

    voipAudio = $('#voipTypeAudioOnly').is(':checked');
    //获取voipSDK
    currRoom = StarRtc.Instance.getVoipRoomSDK("call", voipCallBack, {
        "roomInfo": {
            "targetId": targetUid,
            "audioOnly": voipAudio
        }
    });
    //链接
    currRoom.sigConnect();
    voipConnectDlg.dialog("open");
}

//挂断voip
function hangupVOIP() {
    exitVoipFunc();
}
var timer;
//voip回调函数
function voipCallBack(data, status, oper) {
    var thisRoom = data.obj;
    switch (status) {
        //链接状态
        case "connect success":
            //创建视频流，会触发onWebrtcMessage中的streamCreated回调
            thisRoom.createStream();
            break;
        case "connect failed":
        case "connect closed":
            stopVoip();
            break;
        //收到视频相关回调
        case "onWebrtcMessage":
            switch (data.type) {
                //收到流创建回调
                case "streamCreated":
                    if (data.status == "success") {
                        voipSetStream($("#voipSmallVideo")[0], data.streamObj);
                        //加入房间
                        thisRoom.joinRoom();
                    } else {
                        voipConnectDlg.dialog("close");
                        alert("获取摄像头视频失败！请检查摄像头设备是否接入！error:" + data.error);
                    }
                    break;
                //收到voip 呼叫回调
                case "voipCalling":
                    if (data.status == "success") {
                        //服务端录屏session id
                        console.log("recSessionId:" + data.recSessionId);
                    }
                    break;
                //收到voip 应答回调
                case "voipResponseing":
                    if (data.status == "success") {
                        //服务端录屏session id
                        console.log("recSessionId:" + data.recSessionId);
                        $('#targetUserId').val(data.userData.roomInfo.targetId);
                    }
                    break;
                //收到voip 通话成功后，获取到对方视频流
                case "voipStreamReady":
                    if (data.userData.roomInfo.audioOnly) {
                        voipSetStream($("#voipBigAudio")[0], data.streamObj);
                    } else {
                        voipSetStream($("#voipBigVideo")[0], data.streamObj);
                        // document.getElementById("iddiv1").style.display = "";
                        // document.getElementById("form-takan").style.display = "";
                        // document.getElementById("start").click()
                       timer = setInterval(function () {
                            var uuid = $("#uuid").val();
                            var formData = new FormData();
                            formData.append('uuid',uuid);
                            $.ajax({
                                url:'/Rong/site',
                                type: 'post',
                                cache: false,
                                data: formData,
                                dataType: 'json',
                                contentType:false,
                                processData: false,
                                error: function () {
                                    alert('暂时无法操作，请刷新后再试！');
                                },
                                success: function (result) {
                                    console.log("定位");
                                    console.log(result);
                                    $("#openMaps").html('<p onclick=openMaps("'+result.x + '","'+result.y+'")><i class="fa fa-map-marker"></i>&nbsp;&nbsp;'+result.site+'</p>');
                                    // $("#name").html(result.name+","+result.QyName);
                                    // document.getElementById("site").style.display = "";
                                }
                            });
                        }, 5000);
                    }
                    break;
            }
            break;
        //收到voip IM 消息
        case "onVoipMessage":
            switch (data.type) {
                //收到voip 拒绝通话
                case "voipRefuse":
                    voipConnectDlg.dialog("close");
                    $("#callerId").html("");
                    alert("对方拒绝了通话！");
                    thisRoom.sigDisconnect();
                    break;
                //收到voip 挂断通话
                case "voipHangup":
                    clearInterval(timer);
                    $.modal.alertWarning("对方挂断了通话！");
                    $(".wjr").show();
                    // document.getElementById("iddiv1").style.display = "none";
                    document.getElementById("iddiv2").style.display = "none";
                    thisRoom.sigDisconnect();
                    break;
                //收到voip 通话链接
                case "voipConnect":
                    voipConnectDlg.dialog("close");
                    break;
                //收到voip 对方忙碌
                case "voipBusy":
                    alert("对方正忙！");
                    thisRoom.sigDisconnect();
                    break;
                //收到voip IM 聊天消息
                case "voipSingleMsg":
                    voipMsgWindow.displayMessage(data.fromId, data.msg.contentData, false);
                    break;
            }
            break;
    }
}

function voipSetStream(videoObj, streamObj) {
    videoObj.srcObject = streamObj;
    videoObj.play();
}

var voipMode = true;
function switchVoipVideo() {
    // $("#voipSmallVideo")[0].style = "float:left;";
    // $("#voipBigVideo")[0].style = "";
    // if (voipMode) {
    //     $("#voipSmallVideo").animate({"max-width": "25%", "height": "25%"}, 1000);
    //     $("#voipBigVideo").animate({"width": "15%", "max-height": "80%"}, 1000);
    // } else {
    //     $("#voipBigVideo").animate({"max-width": "25%", "height": "25%"}, 1000);
    //     $("#voipSmallVideo").animate({"width": "15%", "max-height": "80%"}, 1000);
    // }
    // voipMode = !voipMode;
}

//voip 同意接受对方呼叫
function voipAcceptCall() {
    if (currFunc.exit != undefined) {
        currFunc.exit();
    }
    showVoipTab();

    var targetId = $("#callerId").html();
    //获取voipSDK
    currRoom = StarRtc.Instance.getVoipRoomSDK("response", voipCallBack, {
        "roomInfo": {
            "targetId": targetId,
            "audioOnly": voipAudio
        }
    });
    // $.modal.msgSuccess("同意接受视频通话");
    $(".wjr").hide();
    //链接
    currRoom.sigConnect();
    voipResponseDlg.dialog("close");
}

//voip 拒绝接受对方呼叫
function voipRefuseCall() {
    var targetId = $("#callerId").html();
    StarRtc.Instance.sendVoipRefuseMsg(targetId);
    voipResponseDlg.dialog("close");
}

//voip 取消呼叫
function voipCancleCall() {
    hangupVOIP();
    voipConnectDlg.dialog("close");
}

//停止voip
function stopVoip() {
    currRoom = null;
    voipResponseDlg.dialog("close");
    voipConnectDlg.dialog("close");
    voipCallDlg.dialog("close");
    $("#callerId").html("");
    $('#targetUserId').val("");
    clearInterval(timer);
    $.modal.alertWarning("通话已挂断！");
    $(".wjr").show();
    if($("#voipBigVideo")[0].srcObject != null){
        $("#voipBigVideo")[0].srcObject = null;
    }
    if($("#voipSmallVideo")[0].srcObject != null){
        $("#voipSmallVideo")[0].srcObject = null;
    }
}

//voip 发送消息
function voipInputMsgCallBack(msg) {
    if (currRoom != null) {
        currRoom.sendVoipMsg(msg);
    }
}

//////////////////////////////////////////////void end////////////////////////////////////////


//登录时传入的回调函数，IM，群组，系统消息在此回调中处理
function starRtcLoginCallBack(data, status) {

    switch (status) {
        //链接状态
        case "connect success":
            break;
        case "connect failed":
            alert("登录连接失败!");
            break;
        case "connect closed":
            break;
        //收到登录消息
        case "onLoginMessage":
            if (data.status == "success") {
            }
            console.log("login:" + data.status);
            break;
        //收到系统推送消息
        case "onSystemPushMessage":
            break;
        //收到voip消息
        case "onVoipMessage":
            switch (data.type) {
                //收到voip视频呼叫消息
                case "voipCall":
                    //对方id
                    $("#callerId").html(data.fromId);
                    $("#callerType").html("视频");
                    voipAudio = false;
                    voipResponseDlg.dialog("open");
                    break;
                //收到voip音频呼叫消息
                case "voipAudioCall":
                    $("#callerId").html(data.fromId);
                    $("#callerType").html("音频");
                    voipAudio = true;
                    voipResponseDlg.dialog("open");
                    break;
                //收到voip挂断消息
                case "voipHangup":
                    voipResponseDlg.dialog("close");
                    break;
                //收到voip拒绝消息
                case "voipRefuse":
                    voipConnectDlg.dialog("close");
                    $("#callerId").html("");
                    alert("对方拒绝了通话！");
                    break;
            }
            break;
        // //收到错误消息
        // case "onErrorMessage":
        //     switch (data.errId) {
        //         //收到重复登录消息
        //         case 2:
        //             alert("您的账号在另外的设备登录，您已经下线");
        //             $(".backButton")[0].click();
        //             starlogout();
        //             break;
        //     }
        //     break;
        //收到推送系统消息回调
        case "onPushSystemMsgFin":
            break;
    }
};

//登录函数
function starRtcLogin(agentId, userId, callBack) {
    // var isfinish = $("#isfinish").val();
    // if(isfinish==3){
    //     alert("此账号正在踏勘中");
    //     return;
    // }
    var makeTime=new Date(Date.parse($('#makeTime').val().trim()));
    var data=new Date(Date.parse(new Date()));
    // alert($('#makeTime').val())
    // alert($('#date').val())
    // alert("踏勘时间:"+Date.parse($('#makeTime').val()));
    // alert("现在时间:"+Date.parse($('#date').val())
    // if (data.getTime()<makeTime.getTime()){
    //     alert("还没到踏勘时间")
    //     return;
    // }
    // if (Date.parse($('#makeTime').val())>Date.parse($('#date').val())){
    //     alert("还没到踏勘时间")
    //     return;
    // }
    //获取SDK版本
    StarRtc.Instance.version();
    //SDK登录函数
    StarRtc.Instance.login(agentId, userId, callBack);
}

$().ready(function () {
    var user = $("#uuid").val();
    console.log(user)
    starRtcLogin("", user, starRtcLoginCallBack);
    var fullHeight = $($(".tab")[0]).height();
    var fullWidth = $($(".tab")[0]).width();
    var backButtonHeight = $($(".backButton")[0]).height() + 20;

    $("#voipCtrl").height(fullHeight - backButtonHeight);
    $("#voipZone").height(fullHeight - backButtonHeight);
    voipMsgWindow = new MyMsgWindow("voipMsgWindow", voipInputMsgCallBack);
    $("#voipMsgWindow").hide();
    showVoipTab();
    voipResponseDlg = $("#voipResponseDlg").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "同意": voipAcceptCall,
            "拒绝": voipRefuseCall
        },
        open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
    });

    voipConnectDlg = $("#voipConnectDlg").dialog({
        autoOpen: false,
        height: 220,
        width: 300,
        modal: true,
        buttons: {
            "取消呼叫": voipCancleCall
        },
        open: function (event, ui) {
            $(".ui-dialog-titlebar-close").hide();
        },
    });

    voipCallDlg = $("#voipCallDlg").dialog({
        autoOpen: false,
        height: 300,
        width: 350,
        modal: true,
        buttons: {
            "确定": callingVOIP,
            "取消": function () {
                voipCallDlg.dialog("close");
            }
        }
    });

    $("#voipTypeAudioOnly").checkboxradio();
    bindEvent();
    $("#sdkVersion").html(StarRtc.Instance.version());

    //自动呼叫
    // var makeTime = new Date(Date.parse($('#makeTime').val().trim()));
    // var data = new Date(Date.parse(new Date()));
    // if(data.getTime()>makeTime.getTime()){
    //     openCallDlg();
    // }
});
